<?php


namespace app\lib\exception;


use think\Exception;
use think\exception\Handle;
use think\facade\Log;
use think\Response;
use Throwable;

class ExceptionHandle extends Handle
{

    public $httpStatus =500 ;
    private $code;
    private $msg;
    private $errorCode;

    public function render($request, Throwable $e): Response
    {


        if($e instanceof BaseException){
            $this->code = $e->code;
            $this->msg = $e->msg;
            $this->errorCode = $e->errorCode;
        }else{
            if(env('APP_DEBUG', 'true')){
                return parent::render($request, $e);
            }else{
                $this->code =500;
                $this->msg='服务器错误,请联系客服或者稍后再试';
                $this->errorCode=999;
                $this->recordErrorLog($e);
            }
        }

        $result = [
            'msg'  => $this->msg,
            'error_code' => $this->errorCode,
            'request_url' => request()->url()
        ];


// ==========================正式服务器布署===========================
//                $str = <<<EOT
//<html>
//<head>
//<title>Error</title>
//<style>
//    body {
//        width: 35em;
//        margin: 0 auto;
//        font-family: Tahoma, Verdana, Arial, sans-serif;
//    }
//</style>
//</head>
//<body>
//<h1>An error occurred.</h1>
//<p>Sorry, the page you are looking for is currently unavailable.<br/>
//Please try again later.</p>
//<p>If you are the system administrator of this resource then you should check
//the <a href="http://nginx.org/r/error_log">error log</a> for details.</p>
//<p><em>Faithfully yours, nginx.</em></p>
//</body>
//</html>
//EOT;
//return Response::create($str, 'html', 200)->header([])->options([]);
// ==========================正式服务器布署===========================


        // ==================测试服务器布署=====================
        return json($result, $this->code);
    }


    //记录日志
    public function recordErrorLog(Throwable $e){

        Log::record($e->getMessage()."==File:".$e->getFile().$e->getLine(),'info');
    }


}
